//
//  HomeViewController.m
//  TengyunStation
//
//  Created by Johnny on 15/8/21.
//  Copyright (c) 2015年 xingrong. All rights reserved.
//

#import "HomeViewController.h"
#import "SelectedAuthodExpresserViewController.h"
#import "ExpresserViewController.h"
#import "OpenSendViewController.h"
#import "MyStationViewController.h"
#import "TakeCodeViewController.h"
#import "EverydayExpressViewController.h"
#import "DaishouExpressViewController.h"
#import "NetworkViewController.h"
#import "UIWebViewController.h"
#import "Singleton.h"
#import "UIImage+UIColor.h"
#import "SocketRequest.h"
#import "AdModelGroup.h"
#import "StatisticsCount.h"
#import "HomeDropButton.h"
#import "NoviceView.h"
#import "UserAgreementView.h"

@interface HomeViewController ()<SocketRequestDelegate,HomeDropButtonDelegate,UserAgreementViewDelegate> {
    SocketRequest *_socketRequest;
    NSMutableArray *_adGroupList;
    UIButton *_userBtn;
    NSTimer *_messageTimer;
    
    UIButton *_waitSureBtn;//待确认接收
    UILabel *_waitNumberLabel;
}

@end

@implementation HomeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"腾云小站";
        _socketRequest = [[SocketRequest alloc] initWithSocketRequestDelegate:self];
        _adGroupList = [NSMutableArray arrayWithCapacity:1];
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
    [self reloadTongjiData];
    [self getExpressNumberSocket];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self addUserButton];
    [self addRightButton];
    if (!iPhone5Later) {
        _waitBtn.frame = CGRectMake(_waitBtn.frame.origin.x, 15, _waitBtn.frame.size.width, 130);
        _waitView.center = _waitBtn.center;
        _takeBtn.frame = CGRectMake(_takeBtn.frame.origin.x, _waitBtn.frame.origin.y + _waitBtn.frame.size.height + 8, _takeBtn.frame.size.width, 112);
        _takeView.center = _takeBtn.center;
        _returnBtn.frame = CGRectMake(_returnBtn.frame.origin.x, _takeBtn.frame.origin.y + _takeBtn.frame.size.height + 8, _returnBtn.frame.size.width, 130);
        _returnView.center = _returnBtn.center;
        _everyBtn.frame = CGRectMake(_everyBtn.frame.origin.x, _takeBtn.frame.origin.y + _takeBtn.frame.size.height + 8, _everyBtn.frame.size.width, 130);
        _everyView.center = _everyBtn.center;
    }
    [self readAdModelCache];
    [self getAdSocket];
    [self handelNetWorkMethod];
    [self getUserMessageNumberSocket];
    _messageTimer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(getUserMessageNumberSocket) userInfo:nil repeats:YES];
    //判断是否已经同意过协议
    BOOL isShowAgreement = [[[NSUserDefaults standardUserDefaults] objectForKey:FirstAgreement] boolValue];
    if (!isShowAgreement) {
        UserAgreementView *agreementView = [[UserAgreementView alloc] initWithDelegate:self];
        [agreementView show];
    } else {
        //判断是否是第一次打开首页，显示新手引导
        [self showHomeGuide];
    }
}

- (void)addRightButton {
    HomeDropButton *button = [[HomeDropButton alloc] initWithDelegate:self InView:self.view];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}

//添加用户按钮
- (void)addUserButton {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 22, 22);
    button.tag = 105;
    [button setImage:[UIImage imageNamed:@"home_nav_user"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    _userBtn = button;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}

//获取数量
- (void)getExpressNumberSocket {
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STR8"]];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    [_socketRequest addSocketData:mutableData SocketTag:1];
}

//获取广告
- (void)getAdSocket {
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STO4"]];
    [mutableData appendBytes:[@"01" UTF8String] length:2];
    [_socketRequest addSocketData:mutableData SocketTag:2];
}

//获取消息和余额
- (void)getUserMessageNumberSocket {
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STUB"]];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.userId] length:64];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    [_socketRequest addSocketData:mutableData SocketTag:3];
}

//刷新快递数量
- (void)reloadExpressNumber:(NSString *)string {
    NSArray *array = [string componentsSeparatedByString:@","];
    int ziti = [[SocketMethod subArray:array Index:0] intValue];
    int visit = [[SocketMethod subArray:array Index:1] intValue];
    _receiveNumberLabel.text = [NSString stringWithFormat:@"今日已收:%d件",(ziti + visit)];
    int waiTake = [[SocketMethod subArray:array Index:2] intValue];
    _waitTakeNumberLabel.text = [NSString stringWithFormat:@"待取件:%d件",waiTake];
}

- (void)reloadTongjiData {
    if (!_waitSureBtn) {
        _waitSureBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
        _waitSureBtn.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];
        _waitSureBtn.tag = 399;
        [_waitSureBtn addTarget:self action:@selector(topWaitMessage) forControlEvents:UIControlEventTouchUpInside];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 11, 22, 22)];
        imageView.image = [UIImage imageNamed:@"network_logo"];
        [_waitSureBtn addSubview:imageView];
        _waitNumberLabel = [[UILabel alloc] initWithFrame:CGRectMake(44, 12, 250, 20)];
        _waitNumberLabel.backgroundColor = [UIColor clearColor];
        _waitNumberLabel.font = [UIFont systemFontOfSize:14];
        _waitNumberLabel.textColor = [UIColor whiteColor];
        [_waitSureBtn addSubview:_waitNumberLabel];
        UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(290, 11, 22, 22)];
        imageView1.image = [UIImage imageNamed:@"netwrok_next"];
        [_waitSureBtn addSubview:imageView1];
    }
    if ([Singleton shareInstance].statisticsCount.waitExpressesCount > 0) {
        if (![self.view viewWithTag:399]) {
            [self.view addSubview:_waitSureBtn];
        }
        _waitNumberLabel.attributedText = [self tongjiNumberAttrString];
    } else {
        if ([self.view viewWithTag:399]) {
            [_waitSureBtn removeFromSuperview];
        }
    }
    _waitNumber1Label.text = [NSString stringWithFormat:@"待接收:%d批",[Singleton shareInstance].statisticsCount.waitExpressesCount];
    _userBtn.selected = [Singleton shareInstance].statisticsCount.isNewMesasge;
}

- (void)topWaitMessage {
    [MobClick event:@"shouye_btn_daijieshoukuaidixiaoxi"];
    [self jumpDEVC];
}

- (void)jumpDEVC{
    DaishouExpressViewController *daishouEVC = [[DaishouExpressViewController alloc] initWithNibName:@"DaishouExpressViewController" bundle:nil];
    [self.navigationController pushViewController:daishouEVC animated:YES];
}

- (NSAttributedString *)tongjiNumberAttrString {
    NSString *number = [NSString stringWithFormat:@"%d",[Singleton shareInstance].statisticsCount.waitExpressesCount];
    NSString *allString = [NSString stringWithFormat:@"您有%@批快件待接收，请尽快处理~",number];
    NSRange range = [allString rangeOfString:number];
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:allString];
    [attrString addAttribute:NSForegroundColorAttributeName value:OrangeColor range:range];
    return attrString;
}

//显示首页新手指引
- (void)showHomeGuide {
    BOOL isShowHome = [[[NSUserDefaults standardUserDefaults] objectForKey:FirstGuideHome] boolValue];
    if (!isShowHome) {
        [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:FirstGuideHome];
        [[NSUserDefaults standardUserDefaults] synchronize];
        NoviceView *noviceView = [[NoviceView alloc] initWithType:NoviceTypeHome];
        [noviceView show];
    }
}

//用户协议
#pragma mark UserAgreementViewDelegate
- (void)userAgreementViewAgreeAction {
    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:FirstAgreement];
    [[NSUserDefaults standardUserDefaults] synchronize];
    //判断新手指引是否已经显示过
    [self showHomeGuide];
}

#pragma mark HomeDropButtonDelegate
- (void)didFinishHomeDropButtonTag:(NSInteger)tag {
    if (tag == 0) {
        [MobClick event:@"shouye_btn_ziti"];
        SelectedAuthodExpresserViewController *expresserVC = [[SelectedAuthodExpresserViewController alloc] initWithNibName:@"SelectedAuthodExpresserViewController" bundle:nil];
        expresserVC.expressSendType = ExpressSendTypeZiti;
        [self.navigationController pushViewController:expresserVC animated:YES];
    } else if (tag == 1) {
        [MobClick event:@"shouye_btn_shangmen"];
        if ([Singleton shareInstance].userMessage.websiteIsSend) {//表示已开通上面服务
            SelectedAuthodExpresserViewController *expresserVC = [[SelectedAuthodExpresserViewController alloc] initWithNibName:@"SelectedAuthodExpresserViewController" bundle:nil];
            expresserVC.expressSendType = ExpressSendTypeVisit;
            [self.navigationController pushViewController:expresserVC animated:YES];
        } else {
            OpenSendViewController *openSVC = [[OpenSendViewController alloc] initWithNibName:@"OpenSendViewController" bundle:nil];
            [self.navigationController pushViewController:openSVC animated:YES];
        }
    }
}

#pragma makr NibAction
- (IBAction)buttonAction:(id)sender {
    NSInteger tag = 0;
    if ([sender isKindOfClass:NSClassFromString(@"UIButton")]) {
        UIButton *button = (UIButton *)sender;
        tag = button.tag;
    } else if ([sender isKindOfClass:NSClassFromString(@"UITapGestureRecognizer")]) {
        UITapGestureRecognizer *recognizer = (UITapGestureRecognizer *)sender;
        tag = recognizer.view.tag;
    }
    if (tag == 102) {//客户取件
        [MobClick event:@"shouye_btn_qujian"];
        TakeCodeViewController *takecodeVC = [[TakeCodeViewController alloc] initWithNibName:@"TakeCodeViewController" bundle:nil];
        [self.navigationController pushViewController:takecodeVC animated:YES];
    } else if (tag == 103) {//每日件量
        [MobClick event:@"shouye_btn_chaxun"];
        EverydayExpressViewController *everydayEVC = [[EverydayExpressViewController alloc] initWithNibName:@"EverydayExpressViewController" bundle:nil];
        [self.navigationController pushViewController:everydayEVC animated:YES];
    } else if (tag == 104) {//退件
        [MobClick event:@"shouye_btn_tuijian"];
        ExpresserViewController *expresserVC = [[ExpresserViewController alloc] initWithNibName:@"ExpresserViewController" bundle:nil];
        expresserVC.expressSendType = ExpressSendTypeReturn;
        [self.navigationController pushViewController:expresserVC animated:YES];
    } else if (tag == 105) {//用户信息
        [MobClick event:@"shouye_img_gerenzhongxin"];
        _userBtn.selected = NO;
        [Singleton shareInstance].statisticsCount.isNewMesasge = NO;
        [[NSUserDefaults standardUserDefaults] setObject:[Singleton shareInstance].statisticsCount.messageNewTime forKey:[Singleton shareInstance].userMessage.userId];
        [[NSUserDefaults standardUserDefaults] synchronize];
        MyStationViewController *mystationVC = [[MyStationViewController alloc] initWithNibName:@"MyStationViewController" bundle:nil];
        [self.navigationController pushViewController:mystationVC animated:YES];
    } else if (tag == 106) {
        [MobClick event:@"shouye_btn_daijieshoukuaidi"];
        [self jumpDEVC];
    }
}

#pragma mark SocketRequestDelegate
- (void)socket:(GCDAsyncSocket *)socket Code:(NSString *)code Msg:(NSString *)msg Data:(NSData *)data {
    if (socket.socketTag == 1) {//获取首页多少件
        if ([code isEqualToString:SuccessSocket]) {
            NSString *content = [SocketMethod stringDecryHexData:data];
            [self reloadExpressNumber:content];
            DLog(@"%@",content);
        }
    } else if (socket.socketTag == 2) {
        if ([code isEqualToString:SuccessSocket]) {
            NSString *content = [SocketMethod stringDecryHexData:data];
            DLog(@"content:%@",content);
            NSArray *array = [content componentsSeparatedByString:@"|"];
            [AdModel clearTable];
            [_adGroupList removeAllObjects];
            for (NSString *string in array) {
                if (string.length > 0) {
                    AdModel *model = [[AdModel alloc] initWithString:string];
                    [model saveOrUpdate];
                    AdModelGroup *group = nil;
                    for (AdModelGroup *songroup in _adGroupList) {
                        if (songroup.adPosition == model.adPosition) {
                            group = songroup;
                            break;
                        }
                    }
                    if (group) {
                        [group.adList addObject:model];
                    } else {
                        group = [[AdModelGroup alloc] initWithAdModel:model];
                        [_adGroupList addObject:group];
                    }
                }
            }
            [self reloadAdView];
        }
    } else if (socket.socketTag == 3) {
        StatisticsCount *statist = [[StatisticsCount alloc] initWithData:data];
        [Singleton shareInstance].statisticsCount = statist;
        [self reloadTongjiData];
    }
}

- (void)socket:(GCDAsyncSocket *)socket Msg:(NSString *)msg {
    
}

//广告缓存
- (void)readAdModelCache {
    NSArray *array = [AdModel findAll];
    for (AdModel *model in array) {
        AdModelGroup *group = nil;
        for (AdModelGroup *songroup in _adGroupList) {
            if (songroup.adPosition == model.adPosition) {
                group = songroup;
                break;
            }
        }
        if (group) {
            [group.adList addObject:model];
        } else {
            group = [[AdModelGroup alloc] initWithAdModel:model];
            [_adGroupList addObject:group];
        }
    }
    [self reloadAdView];
}

//处理广告
- (void)reloadAdView {
//    _zitiPaomaLabel.adGroup = nil;
//    _visitPaomaLabel.adGroup = nil;
    _takePaomaLabel.adGroup = nil;
    _returnPaomaLabel.adGroup = nil;
    _everyPaomaLabel.adGroup = nil;
    _waitPaomaLabel.adGroup = nil;
    for (AdModelGroup *group in _adGroupList) {
        if (group.adPosition == 3) {
            _takePaomaLabel.adGroup = group;
        } else if (group.adPosition == 4) {
            _returnPaomaLabel.adGroup = group;
        } else if (group.adPosition == 5) {
            _everyPaomaLabel.adGroup = group;
        } else if (group.adPosition == 6) {
            _waitPaomaLabel.adGroup = group;
        }
    }
}

#pragma mark PaomaViewDelegate
- (void)jumpWebViewWithModel:(AdModel *)model {
    UIWebViewController *webVC = [[UIWebViewController alloc] initWithNibName:@"UIWebViewController" bundle:nil];
    webVC.title = @"腾云小站";
    webVC.webUrl = model.link;
    [self.navigationController pushViewController:webVC animated:YES];
}

- (void)stopTimer {
//    [_zitiPaomaLabel clearTimer];
//    [_visitPaomaLabel clearTimer];
    [_waitPaomaLabel clearTimer];
    [_takePaomaLabel clearTimer];
    [_returnPaomaLabel clearTimer];
    [_everyPaomaLabel clearTimer];
    [_messageTimer invalidate];
}

- (void)dealloc {
    _socketRequest = nil;
    _adGroupList = nil;
}

@end
